package com.charm.watercress.ui.fragment

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.charm.codes.mvp.factory.CreatePresenter
import com.charm.codes.mvp.view.AbstractFragment
import com.charm.watercress.R
import com.charm.watercress.adapter.BookAdapter
import com.charm.watercress.constract.presenter.BookPresenter
import com.charm.watercress.constract.view.BookView
import com.charm.watercress.entity.BookEntity
import kotlinx.android.synthetic.main.fragment_film.*
/**
 * Created by tools on 2018/1/11.
 */
@CreatePresenter(BookPresenter::class)
@Route(path = "/watercress/book")
class BookFragment : AbstractFragment<BookView, BookPresenter>(), BookView {
    var page = 1
    private lateinit var adapter: BookAdapter
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_film, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        rv.layoutManager = LinearLayoutManager(context)
        initListener()
        initData()
    }

    private fun initData() {
        mvpPresenter.bookList(page)
        rv.adapter = adapter
    }

    private fun initListener() {
        adapter = BookAdapter(null)
        adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT)
        refresh.setOnRefreshListener {
            page = 1
            adapter.data.clear()
            mvpPresenter.bookList(page)
        }

        adapter.setOnLoadMoreListener({
            page++
            mvpPresenter.bookList(page)
        }, rv)
    }
    override fun bookList(list: List<BookEntity>) {
        adapter.addData(list)
        netComplete()
    }

    override fun netComplete() {
        if (refresh.isRefreshing) {
            refresh.finishRefresh()
        }
        if (adapter.isLoading) {
            adapter.loadMoreComplete()
        }
    }
}